import Vue from 'vue';
import config from '@/config/appidConfig.js'
import user from '@/core/user.js'
const getMiniHeader = (options) => {
	let header = options.header || {}
	header['Content-Type'] = 'application/json' //; charset=utf-8
	// header['kt-brand-id'] = config.ktBrand
	// header['kt-version'] = config.ktVersion
	// header['kt-platform'] = Vue.prototype.$platform
	header['Ba-User-Token'] = uni.getStorageSync('_access_token');
	header['X-Requested-With'] = "XMLHttpRequest"
	header['server'] = '1'

	return header
}
function showMsg(msg, icon = 'none', duration = 1500, error = true) {
	uni.showToast({
		title: msg,
		icon: icon,
		duration: duration,
		mask: true
	})
	// if (error) {
	// 	throw new Error('')
	// }
}

const request = (options = {}, showLoading = true) => {
	options.header = getMiniHeader(options)
	if (options.url == 'api/qa/answer') options.header['Content-Type'] = 'application/x-www-form-urlencoded';
	if (options.url == 'api/miniApp/passport/login') options.header['kt-access-token'] = '';
	options.url = `${config.baseUrl}${options.url}`
	if (showLoading) {
		// uni.showLoading({
		// 	title: '加载中...',
		// 	mask: true
		// })
	}
	return new Promise((resolve, reject) => {
		options.success = ({ statusCode, data: datae }) => {
			// uni.hideLoading()
			if (datae.code !== 1) {
				// Vue.prototype.$isResolve()
				console.log(datae,'状态码')
				showMsg(datae.msg)
				// resolve({ code, msg, _data })
				// return
			}
			let { code, msg, data } = datae
			let _data = datae.data
			// if (code != 0) {
			// 	// showMsg(typeof msg == 'object' ? msg[0] : msg)
			// 	if (code >= 1000 && code <= 1999) {
			// 		logInAgain()
			// 	}
			// }
			// console.log(_data);
			resolve({ code, msg, _data })
		}
		options.fail = (err) => {
			// uni.hideLoading()
			Vue.prototype.$isResolve()
			// showMsg('抱歉，服务器开会儿小差，请稍后重试')
			reject(err)
		}
		options.complete = (res) => {
			// console.log('complete', res);
			// uni.hideLoading({
			// 	complete: function (hide) {
			// 		// console.log('hide', hide);
			// 		if (res.statusCode !== 200) {
			// 			Vue.prototype.$isResolve()
			// 			showMsg('抱歉，服务器开会儿小差，请稍后重试')
			// 			return
			// 		}
			// 		if (res.data.code != 1) {
			// 			showMsg(typeof res.data.msg == 'object' ? res.data.msg[0] : res.data.msg)
			// 			if (res.data.code >= 1000 && res.data.code <= 1999) {
			// 				logInAgain()
			// 			}
			// 		}
			// 	}
			// })

		}
		uni.request(options)
	})
}

const uploadFile = async (options) => {
	const header = getMiniHeader(options)
	return await uni.uploadFile({
		url: miniHost + options.url,
		filePath: options.filePath,
		name: options.name,
		header: header,
		formData: options.data
	})
}
const logInAgain = () => {
	Vue.prototype.$user.clearSilentLoginInst();
	Vue.prototype.$user.silentLogin().then(_login => {
		if (_login.code == 0) Vue.prototype.$isResolve()
	})
}
export {
	request, uploadFile
}

export default request;